<template>
  <div>
    <!-- 地址  -->
    <div class="address" @click="$router.push('/a-list?id='+address.id)">
      <!-- 有地址  -->
      <div v-if="address.id">
        <h3 class="text-primary h2">{{address.username}}{{address.userphone}}</h3>
        <div>
          <van-tag type="danger" v-if="address.status===1">默认</van-tag>
          <van-tag type="danger" v-if="address.label">{{address.label}}</van-tag>
          <span class="p">{{address.location + address.useraddress}}</span>
        </div>
      </div>
      <!-- 无地址 -->
      <van-button v-else>点击完善收货地址</van-button>
    </div>
    <!-- 购物车  -->
    <van-card
      v-for="item in shopList"
      :key="item.id"
      :num="item.num"
      :price="item.price"
      :title="item.goodsname"
      :thumb="$pre+item.img"
    />
    <!-- 结算的栏目 -->
    <van-submit-bar :price="allPrice*100" button-text="提交订单" @submit="onSubmit" />
  </div>
</template>

<script>
import { reqaddresslist, reqcartlist, reqorderadd } from "../../http/http";
import { Toast } from 'vant';
export default {
  data() {
    return {
      address: {},
      shopList: [],
      allPrice: JSON.parse(sessionStorage.getItem("toOrderInfo")).countmoney
    };
  },
  mounted() {
    if (this.$route.query.addressId) {
      reqaddresslist({
        id: this.$route.query.id,
        uid: JSON.parse(localStorage.getItem("isLogin")).uid
      }).then(res => {
        if (res.data.code === 200) {
          this.address = res.data.list[0];
        }
      });
    } else {
      reqaddresslist({
        uid: JSON.parse(localStorage.getItem("isLogin")).uid,
        status: 1
      }).then(res => {
        let list = res.data.list ? res.data.list : [];
        if (list.length === 0) {
          this.address = {};
        }
        if (list.length > 0) {
          let obj = list[0];
          if (obj.status === 1) {
            this.address = obj;
          } else {
            this.address = {};
          }
        }
      });
    }
    let idstr = JSON.parse(sessionStorage.getItem("toOrderInfo")).idstr;
    idstr.split(",").forEach(id => {
      reqcartlist({
        uid: JSON.parse(localStorage.getItem("isLogin")).uid,
        id
      }).then(res => {
        if (res.data.code === 200) {
          this.shopList.push(res.data.list[0]);
        }
      });
    });
  },
  methods: {
    onSubmit() {
      if(!this.address.id){
        Toast("请选择地址");
        return;
      }
      reqorderadd({
        uid: JSON.parse(localStorage.getItem("isLogin")).uid,
        addressid:this.address.id,
        ...JSON.parse(sessionStorage.getItem("toOrderInfo"))
      }).then(res=>{
        if(res.data.code===200){
          sessionStorage.removeItem("toOrderInfo")
          this.$router.replace("/pay?orderId="+res.data.list.outTradeNo)
        }
      })
    }
  }
};
</script>

<style scoped lang="less">
@import "../../less/index.less";
.address {
  padding: @margin20;
  background: #efefef;
}
</style>